import { findBlock, findPara } from '../find';

let root;
let selection, range;

const stack = [];
const maxSize = 100;

function setRoot(a){
  if(typeof a === 'string') {
    root = document.querySelector(a);
  }
  else if(a instanceof Node) {
    root = a;
  }
  else {
    console.error(`operation stack set root: root-${root} is not a string or node`);
  }
}

function record() {
  selection = window.getSelection();
  if(!selection.rangeCount) return;
  range = selection.getRangeAt(0);

  let sc = range.startContainer, ec = range.endContainer,
    sp = findPara(sc), ep = findPara(ec),
    sb = findBlock(sc), eb = findBlock(ec);

  let blocks = Array.from(root.children);

  let sidx = sb === root ? blocks.indexOf(sp) : blocks.indexOf(sb);
  let eidx = eb === root ? blocks.indexOf(ep) : blocks.indexOf(eb);

  let start = blocks.slice(0, sidx).reduce((a, b) => {
    return a + b.outerHTML.length;
  }, 0);
  let end = blocks.slice(eidx + 1, blocks.length).reduce((a, b) => {
    return a + b.outerHTML.length;
  }, 0);
  let content = blocks.slice(sidx, eidx + 1).reduce((a, b) => {
    return a + b.outerHTML
  }, "");

  let record = {
    start,
    end,
    content
  };

  stack.push(record);

  if(stack.length > maxSize) {
    stack.unshift();
  }
}

function revoke() {
  if(!stack.length) return;

  let r = stack.pop();
  let html = root.innerHTML;
  let before = html.slice(0, r.start);
  let after = r.end === 0 ? '' : html.slice(-1 * r.end);
  root.innerHTML = before + r.content + after;

  root.blur();
}

export {
  setRoot,
  record,
  revoke
}